package com.pshcp.patient.task.job;

import cn.hutool.core.date.DateUtil;
import com.pshcp.common.enums.UnPayNotifyEnum;
import com.pshcp.domain.model.OrderReg;
import com.pshcp.manager.messagenotification.MessageNotificationDTO;
import com.pshcp.manager.messagenotification.MessageNotificationManager;
import com.pshcp.patient.tool.OrderRegTools;
import com.pshcp.service.OrderRegService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

/**
 * 未支付订单提醒
 *
 * @author ww
 */
@Slf4j
@Component
public class RegOrderUnPayMsgJob extends QuartzJobBean {

    /**
     * 超时未支付提醒
     */
    @Value("${custom.patient.un-pay-notify:5}")
    private Integer unPayNotify;

    /**
     * 超时未支付提醒
     */
    @Value("${custom.patient.un-pay-timeout:15}")
    private Integer unPayTimeout;

    @Autowired
    private OrderRegService orderRegService;

    @Autowired
    private MessageNotificationManager messageNotificationManager;

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info("start RegOrderCancelJob");
        Date timeoutTime = DateUtil.offsetMinute(new Date(), -unPayNotify);
        //get cancel reg order
        List<OrderReg> orderRegs = orderRegService.unPayList(timeoutTime);
        if(CollectionUtils.isEmpty(orderRegs)){
            log.info("timeout un pay reg order is null. ignore task.");
            return;
        }
        orderRegs.forEach(o -> {
            //send msg
            MessageNotificationDTO dto = OrderRegTools.buildTimeoutUnPayOrderMessage(o, unPayTimeout);
            messageNotificationManager.sendMessageNotification(dto);
            //update notify status
            o.setUnPayNotify(UnPayNotifyEnum.YES.getCode());
            orderRegService.update(o);
        });
        log.info("over RegOrderUnPayMsgJob");
    }

}
